<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>生成器函数</title>
  </head>
  <body>
    <script>
      /*
        Generator  yield 可以暂停生成器函数 
            -done属性结果为true标识已经结束
        */
      function* fn() {
        try {
          console.log("start");
          const res = yield "01";
          console.log(res); //这里会打印boo
        } catch (e) {
          console.log(e);
        }
      }
      const generator = fn(); //不会立即执行而是得到一个生产器对象
      generator.next("boo"); //每执行一次 执行一个yield语句
      generator.throw(new Error("err")); //可以通过try catch捕获

      //异步方案
      function ajax(url) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open("get", url);
          xhr.responseType = "json";
          xhr.onload = function () {
            if (this.status === 200) {
              resolve(this.response);
            } else {
              reject(new Error(this.statuseText));
            }
          };
          xhr.send();
        });
      }
      function* main() {
        const res = yield ajax("./nodes/data.json");
        console.log(res);
        const res2 = yield ajax("./nodes/data1.json");
      }
      const g = main();
      //   const res = g.next();
      //   res.value.then((data) => {
      //     console.log(data);
      //   });
      //递归执行Generator
      function handleResult(result) {
        if (result) return;
        result.value.then(
          (data) => {
            handleResult(g.next(data));
          },
          (err) => {
            g.then(err);
          }
        );
      }
      handleResult(g.next());
      //实现发号气器 id自增
      function* creatId() {
        let id = 1;
        while (true) {
          yield id++;
        }
      }
    </script>
  </body>
</html>
